package tables

import (
	"encoding/csv"
	"os"
	"sync/atomic"

	"github.com/pkg/errors"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
)

var (
	tableTitle = []string{"code", "message", "deprecated", "new_message"} // 表抬头
)

// Table 表格映射
type Table struct {
	Message atomic.Value
}

// NewTable .
func NewTable() *Table {
	return &Table{
		Message: atomic.Value{},
	}
}

// GetCodeMessage .
func (t *Table) GetCodeMessage(code string) string {
	m := t.Message.Load().(map[string]string)
	message, _ := m[code]
	return message
}

// LoadTable .
func (t *Table) LoadTable(tablePath string) error {
	file, err := os.Open(tablePath)
	if err != nil {
		return errors.Wrapf(err, "打开%s路径表格文件失败", tablePath)
	}
	defer file.Close()
	reader := csv.NewReader(transform.NewReader(file, simplifiedchinese.GBK.NewDecoder()))
	tables, err := reader.ReadAll()
	if err != nil {
		return errors.Wrap(err, "读取表格信息失败")
	}
	if len(tables) > 0 {
		// 排除只有抬头空文件
		if len(tables[0]) > 1 {
			// 确认抬头等于预期值
			if tables[0][0] == tableTitle[0] && tables[0][1] == tableTitle[1] &&
				tables[0][2] == tableTitle[2] && tables[0][3] == tableTitle[3] {
				m := make(map[string]string)
				for i := 1; i < len(tables[0]); i++ {
					// 获取新设置的message
					if tables[i][3] != "" {
						m[tables[i][0]] = tables[i][3]
					} else {
						// 默认message
						m[tables[i][0]] = tables[i][1]
					}
				}
				t.Message.Store(m)
				return nil
			}
		}
	}
	return errors.New("csv文件格式或排版不匹配")
}
